<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    private $_id;
    private $_userId;
 
    public function authenticate()
    {
        $record=User::model()->findByAttributes(array('username'=>$this->username));
       
        $salt = openssl_random_pseudo_bytes(22);
        $salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
        $password_hash = crypt($this->password, $salt);
        
        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
     
        else if($record->password !== $password_hash)
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else
        {
            $user= User::model()->findByAttributes(array('id'=>$record->id));
            
            $this->_id=$record->id;
            Yii::app()->session['UserId'] = $user->id;
            $this->setState('roles', $record->roles);    
            $this->setState('id', $record->id);          
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }
 
    public function getId(){
        return $this->_id;
    }
    public function getUserId(){
        return $this->_userId;
    }
}